package com.mingzhi.forum.controller;

import com.mingzhi.forum.common.AppResult;
import com.mingzhi.forum.common.ResultCode;
import com.mingzhi.forum.config.AppConfig;
import com.mingzhi.forum.model.Message;
import com.mingzhi.forum.model.User;
import com.mingzhi.forum.service.IMessageService;
import com.mingzhi.forum.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "站内信接口API")
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private IMessageService messageService;

    @Resource
    private IUserService userService;

    @Operation(summary = "发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @Parameter(description = "接受者id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @Parameter(description = "发送的内容") @RequestParam("content") @NonNull String content) {
        //从session中获取对象
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否禁言
        if (user.getState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //不能给自己发送
        if (receiveUserId == user.getId()) {
            //打印日志
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //查询接收者
        User receiveUser = userService.selectById(receiveUserId);
        if (receiveUser == null || receiveUser.getDeleteState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //构造对象
        Message updateMessage = new Message();
        updateMessage.setPostUserId(user.getId());
        updateMessage.setReceiveUserId(receiveUserId);
        updateMessage.setContent(content);

        //调用业务层
        messageService.create(updateMessage);
        return AppResult.success();
    }

    @Operation(summary = "获取站内信未读数量")
    @PostMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        //根据session获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //进行校验
        if (user == null || user.getDeleteState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //调用service层
        Integer result = messageService.selectUnreadCount(user.getId());
        return AppResult.success(result);
    }

    @Operation(summary = "查询用户的所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        //根据session获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service层
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        return AppResult.success(messages);
    }

    @Operation(summary = "更新站内信状态为已读")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @Parameter(description = "站内信id") @RequestParam("id") @NonNull Long id) {
        //根据站内信id查询内容
        Message message = messageService.selectById(id);
        if (message == null || message.getDeleteState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //获取用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //进行校验
        if (message != null && user.getId() != message.getReceiveUserId()) {
            log.warn("查询了不属于自己的站内信 userId = " + user.getId() + ", receiveUserId = " + message.getReceiveUserId());
            return AppResult.failed(ResultCode.FAILED);
        }
        messageService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }

    @Operation(summary = "回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @Parameter(description = "要回复的站内信id") @RequestParam("repliedId") @NonNull Long repliedId,
                           @Parameter(description = "站内信的内容") @RequestParam("content") @NonNull String content) {
        //获取用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //根据站内信id查询内容
        Message existsMessage = messageService.selectById(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }

        //进行校验
        if (existsMessage != null && user.getId() != existsMessage.getReceiveUserId()) {
            log.warn("查询了不属于自己的站内信 userId = " + user.getId() + ", receiveUserId = " + existsMessage.getReceiveUserId());
            return AppResult.failed(ResultCode.FAILED);
        }

        //构造对象
        Message updateMessage = new Message();
        updateMessage.setPostUserId(user.getId());//发送者
        updateMessage.setReceiveUserId(existsMessage.getPostUserId());
        updateMessage.setContent(content);
        messageService.reply(repliedId,updateMessage);
        return AppResult.success();
    }
}
